package com.wly.data
{
	import com.wly.dbc.XmlReader;
	
	import flash.display.Loader;
	import flash.net.URLLoader;
	import flash.utils.Dictionary;

	public class ResourceCache
	{
		static private var _instance:ResourceCache;
		private var _loader:Loader;
		private var _dic:Dictionary;
		
		static public var TYPEXMLFILE:String = "types.xml";
		static public var ITEMXMLFILE:String = "items.xml";
		
		private var _initComplete:Function;
		
		public function ResourceCache()
		{
			_dic = new Dictionary();
		}
		
		public function init(onInitComplete:Function):void
		{
			_initComplete = onInitComplete;
			loadDBC();
		}
		
		static public function getInstance():ResourceCache
		{
			if(!_instance)
			{
				_instance = new ResourceCache();
			}
			
			return _instance;
		}
		
		public function addResourseByUrl(url:String, data:*):void
		{
			_dic[url] = data;
		}
		
		public function getResourseByUrl(url:String):*
		{
			return _dic[url];
		}
		
		private function loadDBC():void
		{
			var urls:Array = [];
			urls.push(TYPEXMLFILE);
			urls.push(ITEMXMLFILE);
			
			var batchLoader:XmlBatchLoader = new XmlBatchLoader();
			batchLoader.startLoadXmls(urls, onDBCLoadComplete);
		}
		
		private function onDBCLoadComplete():void
		{
			XmlReader.parserTypeXml(getResourseByUrl(TYPEXMLFILE));
			XmlReader.parserItemXml(getResourseByUrl(ITEMXMLFILE));
			
			var i:int;
			var item:ItemVO;
			var itemsUrl:Array = [];
			for(i=0; i<ItemPool.getInstance().getItemList().length; i++)
			{
				item = ItemPool.getInstance().getItemList()[i] as ItemVO;
				if(item)
				{
					itemsUrl.push(item.url);
				}
			}
			
			var batchLoader:AssetBatchLoader = new AssetBatchLoader();
			batchLoader.startLoadAssets(itemsUrl, onItemsImgLoadComplete);
		}
		
		private function onItemsImgLoadComplete():void
		{
			if(_initComplete != null)
			{
				_initComplete();
			}
		}
	}
}